package com.library.servlet;

import com.library.util.DBUtil;
import org.json.JSONObject;
import org.json.JSONArray;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/api/myListings")
public class MyListingsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("userId") == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401 Unauthorized
            JSONObject jsonResponse = new JSONObject();
            jsonResponse.put("success", false);
            jsonResponse.put("message", "用户未登录");
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(jsonResponse.toString());
            return;
        }

        int userId = (int) session.getAttribute("userId");
        String searchTerm = request.getParameter("q");

        List<JSONObject> books = new ArrayList<>();
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT * FROM books WHERE uploader_id = ? ";
            if (searchTerm != null && !searchTerm.trim().isEmpty()) {
                sql += "AND (title LIKE ? OR author LIKE ? OR isbn LIKE ? OR publisher LIKE ? OR category LIKE ?)";
            }
            sql += " ORDER BY create_time DESC";

            try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                pstmt.setInt(1, userId);
                int paramIndex = 2;
                if (searchTerm != null && !searchTerm.trim().isEmpty()) {
                    for (int i = 0; i < 5; i++) {
                        pstmt.setString(paramIndex++, "%" + searchTerm + "%");
                    }
                }

                try (ResultSet rs = pstmt.executeQuery()) {
                    while (rs.next()) {
                        JSONObject book = new JSONObject();
                        book.put("id", rs.getInt("id"));
                        book.put("title", rs.getString("title"));
                        book.put("author", rs.getString("author"));
                        book.put("isbn", rs.getString("isbn"));
                        book.put("publisher", rs.getString("publisher"));
                        book.put("publish_date", rs.getString("publish_date"));
                        book.put("category", rs.getString("category"));
                        book.put("total_copies", rs.getInt("total_copies"));
                        book.put("available_copies", rs.getInt("available_copies"));
                        book.put("image_path", rs.getString("image_path"));
                        book.put("status", rs.getString("status"));
                        book.put("uploader_id", rs.getInt("uploader_id"));
                        books.add(book);
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // 500 Internal Server Error
            JSONObject jsonResponse = new JSONObject();
            jsonResponse.put("success", false);
            jsonResponse.put("message", "数据库操作失败: " + e.getMessage());
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(jsonResponse.toString());
            return;
        }

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(new JSONArray(books).toString());
    }
} 